<template>
  <div class="dynamic">
    <div v-if="data && data.length">
      <div v-for="(item, index) in data" :key="index" class="dynamic-box">
        <div class="dy-icon">
          <i
            v-if="item.category === 'follow'"
            class="V7_iconfont V7_iconV7tubiao_gerenshezhi-bianji1"
          ></i>
          <i
            v-if="item.category === 'workorder'"
            class="V7_iconfont V7_iconV7tubiao_gongdanjilu"
          ></i>
          <i
            v-if="item.category === 'webchat'"
            class="V7_iconfont V7_iconV7tubiao_lianluojilu"
          ></i>
          <i
            v-if="item.category === 'call'"
            class="V7_iconfont V7_iconV7tubiao_waihu"
          ></i>
        </div>
        <div class="title">
          <div class="name">
            <span style="cursor: pointer" @click="showDetail(item)">
              {{ item.title }}</span
            >
            <AudioProgress
              style="margin-left: 10px"
              v-if="item.category === 'call' && item.content.recordFileUrl"
              :row="{
                audioDuration: item.content.recordDuration,
                _id: index + Math.random(),
              }"
              :url="item.content.recordFileUrl"
              :showDowload="
                limitArr.indexOf('download') > -1 &&
                limitArr.indexOf('audition') > -1
              "
              :showListen="limitArr.indexOf('audition') > -1"
            ></AudioProgress>
          </div>
          <div class="time">
            {{ item.datetime }}
            <el-dropdown
              v-if="item.category === 'follow'"
              style="margin-left: 15px"
            >
              <span class="el-dropdown-link">
                <i class="el-icon-more-outline"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="delTrack(item)"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <div v-if="item.category === 'follow'">
          <div class="follow">{{ item.content.memo }}</div>
          <div class="person">
            <span class="label-name">操作人:</span> {{ item.agent }}
          </div>
        </div>
        <div v-if="item.category === 'workorder'" class="workorder">
          <div class="basic">
            <div class="name">{{ item.content.orderCategory }}</div>
            <div v-if="!item.ccAccountld" class="status">
              {{ item.orderStatus }}
            </div>
          </div>
          <div class="info">
            <span style="margin-right: 28px"
              ><span class="label-name">创建人:</span>
              {{
                item.ccAccountId ? item.content.agentName : item.creater
              }}</span
            >
            <span style="margin-right: 28px"
              ><span class="label-name">当前跟进:</span>
              {{ item.ccAccountId ? "--" : item.master }}</span
            >
            <span
              ><span class="label-name">工单编号:</span>
              {{ item.content.orderNo }}</span
            >
          </div>
        </div>
        <div v-if="item.category === 'webchat'" class="webchat">
          <Label v-if="item.tags && item.tags.length" :labelData="item.tags" />
          <div class="chat">
            <span style="margin: 14px 60px 0 0"
              ><span class="label-name">接待人: </span>{{ item.agent }}</span
            >
            <span style="margin: 14px 60px 0 0"
              ><span class="label-name">技能组: </span
              >{{ item.queueNumber }}</span
            >
            <span style="margin: 14px 60px 0 0"
              ><span class="label-name">渠道接入号: </span
              >{{ item.accessName }}</span
            >
            <span style="margin: 14px 60px 0 0"
              ><span class="label-name">结束时间: </span
              >{{ item.content.endTime }}</span
            >
          </div>
        </div>
        <div v-if="item.category === 'call'">
          <Label
            v-if="item.tags && item.tags.length"
            :labelData="item.tags"
            :call="true"
          />
          <div class="chat">
            <span style="margin: 14px 60px 0 0"
              ><span class="label-name">类型: </span
              >{{ item.content.callType | getCallType }}</span
            >
            <span style="margin: 14px 60px 0 0"
              ><span class="label-name">状态: </span
              >{{ item.content.status | getCallStatus }}</span
            >
            <span style="margin: 14px 60px 0 0"
              ><span class="label-name">呼叫人: </span>{{ item.agent }}</span
            >
            <span style="margin: 14px 60px 0 0"
              ><span class="label-name">技能组: </span
              >{{ item.queueNumber }}</span
            >
            <span style="margin: 14px 60px 0 0"
              ><span class="label-name">通话时长: </span
              >{{ item.content.bridgeDuration | getTimeLength }}</span
            >
          </div>
        </div>
      </div>
      <div v-if="moreShow" class="more-btn" @click="loadMore">点击加载更多</div>
      <div v-else class="all">已经到底啦~</div>
    </div>
    <div v-else class="none">暂无客户动态</div>
    <el-dialog
      :visible.sync="workShow"
      :modal="false"
      :show-close="false"
      :class="type === 'call' ? 'call' : 'work'"
    >
      <EditBusiness
        v-if="type === 'workorder' && !bussinessType"
        ref="addOrEditBusinessRef"
        :hiddenBtn="true"
        :agentList="agentListArr"
        @cancelFun="back"
      />
      <OldCusBusiness
        ref="oldCusBusiness"
        v-if="type === 'workorder' && bussinessType"
      />
      <CallDetail
        v-if="type === 'call'"
        :commonData="callData"
        :hiddenLabels="true"
        :showDowload="
          limitArr.indexOf('download') > -1 && limitArr.indexOf('audition') > -1
        "
        :showListen="limitArr.indexOf('audition') > -1"
      />
      <TabWebchatInfo
        v-if="type === 'webchat'"
        :commonData="webchatData"
        module="dynamic"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { deepClone, commonAction, getCallStatusName, getCallTypeName, getCallTimeLength, isHasFuncOrMenus } from '@/utils/common'
import { Component, Vue, Prop, Ref } from 'vue-property-decorator'
import AudioProgress from '@/components/audio/AudioProgress.vue'
import Label from './label.vue'
import EditBusiness from '@/afterSales/views/business/components/editBusiness.vue'
import { CommonModule } from '@/store/modules/common'
import CallDetail from '@/components/commonSummary/detailTab/callDetail.vue'
import TabWebchatInfo from '@/views/dataCenter/webchatData/webchatSessionDetails.vue'
import { WebchatModule } from '@/store/modules/webchat'
import { CallCardModule } from '@/store/modules/cti/callCard'
import OldCusBusiness from '@/views/newCustomer/components/oldCusBusiness.vue'
@Component({
  name: 'Dynamic',
  components: {
    AudioProgress,
    Label,
    EditBusiness,
    CallDetail,
    TabWebchatInfo,
    OldCusBusiness
  },
  filters: {
    getCallStatus (status) {
      return getCallStatusName(status)
    },
    getCallType (type) {
      return getCallTypeName(type)
    },
    getTimeLength (timeLength) {
      return getCallTimeLength(timeLength, false)
    }
  }
})
export default class Dynamic extends Vue {
  [x: string]: any
  @Prop({ default: () => [] }) private data
  @Prop({ default: () => [] }) private moreShow
  @Ref() private readonly addOrEditBusinessRef
  @Ref() private readonly oldCusBusiness

  private webchatData: any = []
  private limitArr: any[] = [] // 权限控制

  private callData: any = {}

  get agentListArr () {
    const agents = deepClone(CommonModule.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ key: agents[i]._id, label: agents[i].name })
    }
    return agentsArr
  }

  private workShow: boolean = false

  private type: any = ''

  private bussinessType: any = 0 // cc迁移的客户为1

  private loadMore () {
    this.$emit('loadMore')
  }

  private delTrack (val: any) {
    const params = {
      url: '/server-crm/action/customer/dynamics/follow/delete',
      method: 'POST',
      data: {
        _id: val._id
      }
    }
    commonAction(params).then(res => {
      if (res.success) {
        this.$emit('updateDynamic')
        this.$message.success('删除成功')
      }
    })
  }

  private back () {
    this.workShow = false
  }

  private getWeChat (visitorId: any, id: any) {
    const url = '/im-center/action/webchat/queryChatInfoById'
    const chatInfoActionData = { url, method: 'POST', data: { visitorId, _id: id } }
    const serveTimeActionData = { url: '/im-center/action/webchat/getServerTimeDiff', method: 'POST', data: { localTimestamp: new Date().getTime() } }
    const queryServeTime = WebchatModule.webchatCommonAction(serveTimeActionData) // 获取服务器时间
    const queryChatInfoById = WebchatModule.queryChatInfoById(chatInfoActionData) // 获取会话详情
    Promise.all([queryChatInfoById, queryServeTime]).then(([chatInfo, serveTime]: any) => {
      if (chatInfo && serveTime && serveTime.serverTime && chatInfo.chatSession) {
        const messageHistoryData = { // 获取消息历史参数
          visitorId,
          dateTime: serveTime.serverTime,
          limit: 20,
          _id: id,
          isNewSession: true,
          webchatType: 'webchatDateCenter',
          sessionId: chatInfo.chatSession._id
        }
        const messageHistoryActionData = { url: '/im-center/action/webchat/queryHistory', method: 'POST', data: messageHistoryData }
        WebchatModule.queryWebchatHistory(messageHistoryActionData).then(res => { // 获取会话历史
          if (res && res.messageList) {
            this.webchatData = {
              type: 'webchat_session',
              importType: 'webchatDataCenter', // 数据中心
              webchatDetails: chatInfo.chatSession, // 在线详情
              processInfo: chatInfo.processInfo, // 流程信息
              visitorInfo: chatInfo.visitorInfo || {} // 访客信息
            }
          }
        })
      }
    }
    )
  }

  private getCallDetail (id) {
    const params = {
      url: '/call/action/cdr/detail',
      method: 'GET',
      data: {
        id
      }
    }
    commonAction(params).then(res => {
      if (res.success && res.data) {
        this.getCall({ callSheetId: res.data._id, phone: res.data.customerNumber, cdr: res.data })
      }
    })
  }

  private getCall (callObj: any) {
    Vue.set(this, 'callData', {
      timeStamp: new Date().getTime(),
      phone: callObj.phone,
      custId: callObj.cdr.customerId,
      custName: callObj.cdr.customerName,
      callSheetId: callObj.callSheetId,
      cdr: callObj.cdr,
      randomNum: Math.random()
    })
  }

  private showDetail (val: any) {
    this.workShow = true
    this.type = val.category
    if (this.type === 'workorder') {
      if (val.ccAccountId) { // cc迁移的客户
        this.bussinessType = 1
        this.$nextTick(() => {
          this.oldCusBusiness.initData(val)
        })
      } else {
        this.bussinessType = 0
        this.$nextTick(() => {
          this.addOrEditBusinessRef.getBusinessDataById({ modelId: val.content.modelId, orderId: val.ref })
        })
      }
    } else if (this.type === 'webchat') {
      this.getWeChat(val.content.visitorId, val.ref)
    } else if (this.type === 'call') {
      this.getCallDetail(val.ref)
    }
  }

  private beforeMount () {
    const arr = ['callSheet_audition', 'callSheet_download'] //  试听，下载,
    arr.forEach((item: string) => {
      if (isHasFuncOrMenus(item, this.$store.state.common.session.user, false)) {
        if (item.indexOf('_audition') > -1) {
          this.limitArr.push('audition')
        }
        if (item.indexOf('_download') > -1) {
          this.limitArr.push('download')
        }
      }
    })
  }
}
</script>

<style lang="stylus" scoped>
.webchatSessionDetails
  height 460px
.work
  >>> .el-dialog__header
    padding 0
    margin-bottom 0
  >>> .el-dialog__body
    padding 0
.call
  >>> .el-dialog__body
    padding 20px
>>> .radio-span
  width 20px
  height 20px
  line-height 20px
  font-size 10px
.dynamic
  height calc(100% - 62px) !important
  overflow auto
  .label-name
    color #686E84
    padding-right 4px
  .none
    text-align center
    color #999
    margin-top 50px
  .dynamic-box
    width 100%
    border 1px solid #ECF0F3
    border-radius 4px
    padding 0 20px
    margin-top 24px
    position relative
    .dy-icon
      width 20px
      height 20px
      background #008BEE
      box-shadow 0px 1px 6px 0px rgba(98,172,224,0.56)
      position absolute
      border-radius 50%
      left 5px
      top -10px
      padding 4px
      i
        color #fff
        font-size 12px
    .title
      height 40px
      border-bottom 1px solid #ECF0F3
      display flex
      justify-content space-between
      align-items center
      .name
        color #008BEE
      .time
        color #686E84
        .el-dropdown-link
          cursor pointer
          color #409EFF
    .webchat
      .labels
        padding 12px 0
        display flex
        align-items center
        flex-wrap wrap
        border-bottom 1px solid #ECF0F3
        .icon
          width 16px
          height 16px
          border-radius 50%
          border 1px solid #E7E9ED
          cursor pointer
        .tag
          max-width 80px
          height 24px
          overflow hidden
          word-break keep-all
          white-space nowrap
          text-overflow ellipsis
          border-radius 24px
          padding 5px 10px
          margin 0 10px 6px 0
    .chat
      padding-bottom 14px
      span
        display inline-block
    .follow
      width 100%
      color #303753
      line-height 22px
      overflow hidden
      text-overflow ellipsis
      display -webkit-box
      -webkit-line-clamp 3
      -webkit-box-orient vertical
      padding 14px 0
      border-bottom 1px solid #ECF0F3
    .person
      height 40px
      line-height 40px
    .workorder
      .basic
        display flex
        justify-content space-between
        margin-top 14px
      .info
        margin 14px 0
  .more-btn
    text-align center
    color #008BEE
    font-size 12px
    cursor pointer
    margin-top 20px
  .all
    color #999
    text-align center
    margin-top 20px
</style>
